package com.itlangzi.mybatis.dialect;

import com.alibaba.druid.util.JdbcConstants;
import com.itlangzi.mybatis.dialect.helper.DialectEnum;
import com.itlangzi.mybatis.dialect.helper.DialectHelper;

/**
 * SQLServer 分页方言
 */
public class SQLServer2012Dialect implements Dialect {

    @Override
    public boolean supportsPage() {
        return true;
    }

    /**
     * sql server中count子句中不能包含order by,否则报错.
     * 默认order by放最后,如果sql复杂,有多个order by嵌套,则不能使用该分页方法,请自行在sql中分页.
     */
    @Override
    public String buildCountSQL(String originalSQL) {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("SELECT COUNT(1) AS TOTAL FROM ( ").append(DialectHelper.getNoneOrderBySQL(originalSQL, JdbcConstants.SQL_SERVER)).append(" ) AS T ");
        return sqlBuilder.toString();
    }

    /**
     * 必须有order by 语句 否则分页报错
     */
    @Override
    public String buildPageSQL(String originalSQL, Integer page, Integer size) {
        StringBuilder sqlBuilder = new StringBuilder(originalSQL.length() + 120);
        sqlBuilder.append(originalSQL);
        sqlBuilder.append(" OFFSET ");
        sqlBuilder.append(page);
        sqlBuilder.append("  ROWS FETCH NEXT  ");
        sqlBuilder.append(size);
        sqlBuilder.append(" ROWS ONLY ");
        return sqlBuilder.toString();
    }

    @Override
    public String getDialectName() {
        return DialectEnum.SQLSERVER.getDbName();
    }
}
